package com.wenxin.springbootcacheconsistency.controller;

import com.wenxin.springbootcacheconsistency.domain.Goods;
import com.wenxin.springbootcacheconsistency.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * @Author: Wenxin
 * @CreateTime: 2024/12/25 15:39
 * @Description: 库存controller
 * @Version: 1.0
 */
@RestController
@RequestMapping("/stock")
public class StockController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PutMapping("/reduce")
    public Boolean reduce(Long goodsId, Long stock) {
        return goodsService.reduceGoodsStock(goodsId, stock);
    }

    @GetMapping("/getStock")
    public Long getStock(Long goodsId) {
        Object o = redisTemplate.opsForHash().get("good_stock", String.valueOf(goodsId));
        if (o == null){
            o = Optional.ofNullable(goodsService.getById(goodsId)).orElse(new Goods()).getStock();
            if (o == null){
                return 0L;
            }
            redisTemplate.opsForHash().put("good_stock", String.valueOf(goodsId), o);
            return (Long) o;
        }
        return Long.parseLong(o.toString());
    }
}
